<template>
    <div class="authority">
        <div class="gva-table-box unit">
            <div class="gva-btn-list">
                <el-button type="primary" icon="plus" @click="addLouDong">新增</el-button>
            </div>
            <el-table :data="tableData">
                <el-table-column type="index" label="序号" width="100" />
                <el-table-column align="left" label="单位名称" prop="name" show-overflow-tooltip></el-table-column>
                <el-table-column align="left" label="单位类别">
                    <template #default="scope">
                        <span>{{ getType(scope.row.unitType) }}</span>
                    </template>
                </el-table-column>
                <el-table-column align="left" label="单位情况">
                    <template #default="scope">
                        <span>{{ qkList[scope.row.situation - 1].name }}</span>
                    </template>
                </el-table-column>
                <el-table-column align="left" label="编制人数" prop="thirdNums"></el-table-column>
                <el-table-column v-for="(item,i) in roomExceeds" align="left" :label="item.roomType" width="120">
                    <template #default="scope">
                        <span>{{ tableData[scope.$index].roomExceed[i].realArea }}</span>
                    </template>
                </el-table-column>
                <!-- <el-table-column align="left" label="办公室" prop="name"></el-table-column>
                <el-table-column align="left" label="服务用房" prop="name"></el-table-column>
                <el-table-column align="left" label="设备用房" prop="name"></el-table-column> -->
                <el-table-column align="left" fixed="right" label="操作" min-width="220">
                    <template #default="scope">
                        <el-button type="primary" link icon="edit" @click="lrLouDong(scope.row)">
                            录入房间
                        </el-button>
                        <el-button type="primary" link icon="edit" @click="editLouDong(scope.row)">
                            编辑
                        </el-button>
                        <el-button type="danger" link icon="delete" @click="delUnit(scope.row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 新增楼栋 -->
        <el-drawer v-model="dialog1" :size="1200" :before-close="handleClose1" :show-close="false"
            class="loudong-drawer">
            <template #header>
                <div class="flex justify-between items-center">
                    <span class="text-lg">{{ dialog1Title }}</span>
                    <div>
                        <el-button @click="closeDialog1">取消</el-button>
                        <el-button type="primary" @click="enterDialog">确定</el-button>
                    </div>
                </div>
            </template>
            <el-form v-if="dialog1" ref="loudongForm" label-width="150" :model="form" :rules="rules">
                <div class="section-title">单位名称</div>
                <el-form-item label="单位名称" prop="name">
                    <el-input v-model="form.name" style="width: 360px" />
                </el-form-item>
                <el-form-item label="单位情况" prop="situation">
                    <el-radio-group v-model="form.situation" class="ml-4">
                        <el-radio v-for="item in qkList" :value="item.id" size="large">{{ item.name }}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="单位类别" prop="unitType">
                    <el-select v-model="form.unitType" placeholder="请选择" style="width: 400px">
                        <el-option v-for="item in lbList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <div class="section-title">办公楼</div>
                <el-form-item label="选择办公区" prop="areaId">
                    <el-select v-model="form.areaId" placeholder="请选择" style="width: 360px" @change="changeArea">
                        <el-option v-for="item in qyList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="选择办公楼" prop="buildingId">
                    <el-select v-model="form.buildingId" placeholder="请选择" style="width: 360px" @change="changeBgl">
                        <el-option v-for="item in bglList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="选择楼层" prop="floorIds">
                    <el-checkbox-group v-model="form.floorIds">
                        <el-checkbox v-for="item in lcList" :label="item.floor" :value="item.id" />
                    </el-checkbox-group>
                </el-form-item>
                <div class="section-title">编制人数</div>
                <el-table :data="sdData" border>
                    <el-table-column type="index" label="序号" width="100" />
                    <el-table-column align="left" label="职级名称" prop="rank"></el-table-column>
                    <el-table-column align="left" label="三定方案人数" prop="numbers">
                        <template #default="scope">
                            <el-input v-model.number="scope.row.numbers"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column align="left" label="核定面积" prop="area"></el-table-column>
                </el-table>
            </el-form>
        </el-drawer>

        <!-- 新增楼栋 -->
        <el-drawer v-model="dialog2" :size="1200" :before-close="handleClose2" :show-close="false"
            class="loudong-drawer">
            <template #header>
                <div class="flex justify-between items-center">
                    <span class="text-lg">录入房间</span>
                    <div>
                        <el-button @click="closeDialog2">取消</el-button>
                        <!-- <el-button type="primary" @click="enterDialog">确定</el-button> -->
                    </div>
                </div>
            </template>
            <div class="bgl">
                <div class=active>{{ fjInfo.name }}</div>
            </div>
            <div class="bgl-info">
                <div class="item">
                    <div class="label">总建筑面积：</div>
                    <div class="value">{{ fjInfo.totalArea }}平方米</div>
                </div>
                <div class="item">
                    <div class="label">占地面积：</div>
                    <div class="value">{{ fjInfo.coverArea }}平方米</div>
                </div>
                <div class="item">
                    <div class="label">总层数:</div>
                    <div class="value">{{ fjInfo.totalFloor }}</div>
                </div>
                <div class="item">
                    <div class="label">建设年代：</div>
                    <div class="value">{{ fjInfo.createYear }}</div>
                </div>
            </div>
            <div style="box-shadow: 0 2px 5px 0 rgba(0, 0, 0, .1);border:1px solid #e6e6e6;">
                <div class="floors">
                    <div v-for="(item, index) in fjInfo.floors"
                        :class="currentFloor == index ? 'floor active' : 'floor'" @click="changeFloor(item, index)">{{
                        item.floor }}</div>
                </div>
                <div style="margin: 10px 0 10px 10px;">
                    <el-button type="primary" @click="addRooms">新增房间</el-button>
                </div>
                <el-table :data="fjData" row-key="id">
                    <el-table-column type="selection" width="55" />
                    <el-table-column type="index" label="序号" width="100" />
                    <el-table-column align="left" label="房号/房名" prop="roomNo">
                    </el-table-column>
                    <el-table-column align="left" label="房间面积" prop="area"></el-table-column>
                    <el-table-column align="left" label="房间类型" prop="roomTypeSec">
                    </el-table-column>
                    <el-table-column align="left" fixed="right" label="操作" min-width="160">
                        <template #default="scope">
                            <el-button type="primary" link icon="edit" @click="editRooms(scope.row)">
                                编辑
                            </el-button>
                            <el-button type="danger" link icon="delete" @click="delRooms(scope.row)">
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-drawer>

        <!-- 新增房间 -->
        <el-drawer v-model="dialog3" :size="1200" :before-close="handleClose3" :show-close="false"
            class="loudong-drawer">
            <template #header>
                <div class="flex justify-between items-center">
                    <span class="text-lg">{{ dialog3Title }}</span>
                    <div>
                        <el-button @click="closeDialog3">取消</el-button>
                        <el-button type="primary" @click="enterDialog3">确定</el-button>
                    </div>
                </div>
            </template>
            <el-form v-if="dialog3" ref="fjForm" label-width="150" :model="fjForms" :rules="fjRules">
                <el-form-item label="房间名" prop="roomId">
                    <el-select v-model="fjForms.roomId" placeholder="请选择" style="width: 200px" @change="changeRoom">
                        <el-option v-for="item in fangjianData" :key="item.id" :label="item.roomNo" :value="item.id" />
                    </el-select>
                    <span style="margin-left: 4px;color: #FF473E;">注：有房号填房号，无房号填房名</span>
                </el-form-item>
                <el-form-item label="房间类型" prop="roomTypeId">
                    <div style="display: flex;">
                        <el-select v-model="fjForms.ssId" placeholder="请选择" style="width: 200px;margin-right: 4px;" @change="changeType">
                            <el-option v-for="item in yfTypeList" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                        <el-select v-model="fjForms.roomTypeId" placeholder="请选择" style="width: 200px">
                            <el-option v-for="item in yfTypes" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                    </div>
                </el-form-item>
                <el-form-item label="房间面积" prop="contact">
                    <el-input v-model="fjForms.area" placeholder="请输入" disabled style="width: 400px" />
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="fjForms.notes" type="textarea" :rows="6" style="width: 400px;" />
                </el-form-item>
            </el-form>
        </el-drawer>
    </div>
</template>
<script setup>
import {
    getAllBgqList,
    getBuildingFloors,
    getFangJianList
} from '@/api/shujuchuli'
import {
    unitRoom,
    buildingAll,
    addBuilding,
    delRoom,
    editBuilding,
    unitBaseInfo,
    createUnit,
    updateUnit,
    juniorList,
    unitSaveStaff,
    deleteUnit,
    unitBuildingById,
    unitStaffById,
    unitBuilding,
    allUr,
    addRoom,
    editRoom
} from '@/api/unit'

import { zjObj,yfTypeList } from '@/utils/constant'
import {
    getDyList
} from '@/api/xitongpeizhi'
import {
    getZjList
} from '@/api/xitongpeizhi'
import { reactive, ref, onMounted } from 'vue'
import { useAppStore } from "@/pinia";
import { useUserStore } from '@/pinia/modules/user'
import { ElMessage, ElMessageBox, useFormItem } from 'element-plus'

defineOptions({
    name: 'Qtdw'
})

const appStore = useAppStore()
const userStore = useUserStore()
const tableData = ref([])
const roomExceeds = ref([])
const getTableData = async () => {
    const res = await juniorList()
    if (res.code == 200) {
        tableData.value = res.result
        if(res.result&&res.result.length>0){
            roomExceeds.value = res.result[0].roomExceed
        }
       
    }
}
getTableData()
const form = ref({
    name: '',
    unitType: '',
    situation: 1,
    areaId: '',
    buildingId: '',
    floorIds: [],
    unitRank: [],
    unitId: '',
    rank:''
})
const qkList = ref([
    {
        name: '下属单位',
        id: 1
    },
    {
        name: '出租',
        id: 2
    },
    {
        name: '出借',
        id: 3
    },
])

const dialog1 = ref(false)
const dialog1Title = ref('新增')
const isEdit = ref(false)
function addLouDong() {
    dialog1Title.value = '新增'
    isEdit.value = false
    dialog1.value = true
}
async function editLouDong(item) {
    isEdit.value = true
    Promise.all([unitBuildingById(item.id), unitStaffById(item.id)]).then(res => {
        form.value = JSON.parse(JSON.stringify(item))
        form.value.areaId = res[0].result[0].areaId
        buildingAll({ areaId: form.value.areaId }).then(res2 => {
            bglList.value = res2.result
            form.value.buildingId = res[0].result[0].buildingId
            form.value.unitBuildingId = res[0].result[0].id
            getBuildingFloors(form.value.buildingId).then(res3 => {
                lcList.value = res3.result
                form.value.floorIds = res[0].result[0].floorIds.split(',').map(item => Number(item))
                form.value.unitId = item.id
                sdData.value = res[1].result
                dialog1Title.value = '编辑单位'
                dialog1.value = true
            })
        })
    })
}
const yfTypes = ref([])
function changeArea(val) {
    form.value.buildingId = ''
    form.value.floorIds = []
    buildingAll({ areaId: val }).then(res => {
        bglList.value = res.result
    })
}
function changeType(val) {
    allUr({ type: val }).then(res => {
        yfTypes.value = res.result
        fjForms.value.roomTypeId = ''
    })
}
function changeBgl(val) {
    form.value.floorIds = []
    let bglObj = bglList.value.find(item => item.id == val)
    //form.value = Object.assign(bglObj, form.value)
    getBuildingFloors(val).then(res => {
        lcList.value = res.result
    })
}
const loudongForm = ref(null)
const enterDialog = async () => {
    loudongForm.value.validate(async (valid) => {
        if (valid) {
            let res1
            let res2
            let res3
            if (Array.isArray(form.value.floorIds)) {
                form.value.floorIds = form.value.floorIds.join(',')
            }
            form.value.unitRank = sdData.value
            if (isEdit.value) {
                res1 = await updateUnit(form.value)
                res2 = await editBuilding(form.value)
                res3 = await unitSaveStaff(form.value)
            } else {
                res1 = await createUnit(form.value)
                form.value.unitId = res1.result.id
                res2 = await addBuilding(form.value)
                //             let params = {
                //     unitId:form.value.unitId,
                //     unitRank:[...sdData.value,...syData.value]
                // }
                res3 = await unitSaveStaff(form.value)
            }
            if (res3.code == 200) {
                ElMessage({
                    type: 'success',
                    message: isEdit.value ? '编辑成功' : '添加成功!'
                })
            }
            getTableData()
            dialog1.value = false
        }
    })
}
const delUnit = (row) => {
    ElMessageBox.confirm(
        '确认删除?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        const res = await deleteUnit(row.id)
        if (res.code === 200) {
            ElMessage({
                type: 'success',
                message: '删除成功!'
            })
            getTableData()
        }
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消删除'
        })
    })
}

function delRooms(row){
    ElMessageBox.confirm(
        '确认删除?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        const res = await delRoom({unitId:searchInfo.value.unitId,roomId:row.id})
        if (res.code === 200) {
            ElMessage({
                type: 'success',
                message: '删除成功!'
            })
            getunitRoom()
        }
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消删除'
        })
    })
}
function handleClose1() {
    dialog1.value = false
}

function closeDialog1() {
    initForm1()
    dialog1.value = false
}
function initForm1() {
    loudongForm.value.resetFields()
    form.value = {
        name: '',
        unitType: '',
        situation: 1,
        areaId: '',
        buildingId: '',
        floorIds: [],
        unitRank: [],
        rank:'',
        unitId: JSON.parse(localStorage.getItem('userInfo')).unitId
    }
}

const page = ref(1)
const total = ref(0)
const pageSize = ref(10)

const rules = reactive({
    areaId: [{ required: true, message: '请选择办公区', trigger: 'change' }],
    buildingId: [{ required: true, message: '请选择办公楼', trigger: 'change' }],
    floorIds: [{ required: true, message: '请选择楼层', trigger: 'change' }],
    unitType: [{ required: true, message: '请选择单位类别', trigger: 'change' }],
    name: [{ required: true, message: '请输入单位名称', trigger: 'blur' }],
    situation: [{ required: true, message: '请选择单位情况', trigger: 'change' }],
})
const fjRules = reactive({
    roomId: [{ required: true, message: '请选择房间名', trigger: 'change' }],
    roomTypeId: [{ required: true, message: '请选择房间类型', trigger: 'change' }],
})
const qyList = ref([])
const bglList = ref([])
const lcList = ref([])
const sdData = ref([])
const lbList = ref([])
onMounted(() => {
    if (localStorage.getItem('userInfo')) {
        form.value.parentId = JSON.parse(localStorage.getItem('userInfo')).unitId
        form.value.unitId = JSON.parse(localStorage.getItem('userInfo')).unitId
    }
    getAllBgqList().then(res => {
        qyList.value = res.result
    })
    getDyList({ pageNumber: 1, pageSize: 100 }).then(res => {
        lbList.value = res.result.data.filter(item => item.type == 2)
    })
    Promise.all([unitBaseInfo(), getZjList()]).then(res => {
        let realName = res[1].result.data.find(item => item.id == res[0].result.rank).realName
        form.value.rank = res[0].result.rank
        let zjArr = realName.split('|')
        for (const key in zjObj) {
            if (zjArr.includes(key)) {
                sdData.value.push({
                    rank: key,
                    area: String(zjObj[key]),
                    numbers: 0,
                    type: 1
                })
            }
        }
    })
})
function getType(val) {
    let res = ''
    let obj = lbList.value.find(item => item.id == val)
    res = obj?.name
    return res
}
const dialog2 = ref(false)
function handleClose2() {
    dialog2.value = false
}
const fangjianData = ref([
    
])
const searchInfo = ref({
    floorId: '',
    buildingId: '',
    name: ''
})
const getFangJianData = async () => {
    const res = await getFangJianList(searchInfo.value.floorId)
    if (res.code == 200) {
        fangjianData.value = res.result
    }
}
const fjInfo = ref({})
const currentFloor = ref(0)
function lrLouDong(item) {
    Promise.all([unitBuildingById(item.id), unitBuilding()]).then(res => {
        //let id = res[0].result[0].buildingId
        //let obj = res[1].result.find(m => m.id == id)
        searchInfo.value.buildingId = res[0].result[0].buildingId
        searchInfo.value.floorId = res[0].result[0].floors[currentFloor.value].id
        fjInfo.value = res[0].result[0]
        searchInfo.value.unitId = res[0].result[0].unitId
        getunitRoom()
        getFangJianData()
        dialog2.value = true
    })
   
}

function changeFloor(item, index) {
    currentFloor.value = index
    console.log(fjInfo.value.floors[currentFloor.value].id,'crjkl')
    searchInfo.value.floorId = fjInfo.value.floors[currentFloor.value].id
    getunitRoom()
    getFangJianData()
}
function getunitRoom() {
    unitRoom(searchInfo.value).then(res => {
        fjData.value = res.result
    })
}

function closeDialog2() {
    dialog2.value = false
}
const fjData = ref([])
const dialog3 = ref(false)
const fjForm = ref(null)
const fjForms = ref({
    roomId: '',
    roomTypeId: '',
    notes: '',
    area: '',
    unitRoomId: '',
    ssId: ''
})
function changeRoom(val) {
    let obj = fangjianData.value.find(item => item.id == val)
    fjForms.value.area = obj.roomArea
}
const dialog3Title = ref('新增')
const isRoomEdit = ref(false)
function addRooms(row) {
    dialog3Title.value = '新增'
    isRoomEdit.value=false
    dialog3.value = true
}
function closeDialog3() {
    initForm3()
    dialog3.value = false
}
function handleClose3() {
    initForm3()
    dialog3.value = false
}
function initForm3() {
    fjForm.value.resetFields()
    fjForms.value = {
        roomId: '',
        roomTypeId: '',
        notes: '',
        area: '',
        unitRoomId: '',
        ssId: ''
    }
}
function editRooms(item) {
    fjForms.value = JSON.parse(JSON.stringify(item))
    fjForms.value.roomId = item.id
    fjForms.value.ssId = yfTypeList.find(m => m.label == item.roomType).value
    allUr({ type: fjForms.value.ssId }).then(res => {
        yfTypes.value = res.result
    })
    dialog1Title.value = '编辑'
    isRoomEdit.value = true
    dialog3.value = true
}
const enterDialog3 = async () => {
    fjForm.value.validate(async (valid) => {
        if (valid) {
            fjForms.value.unitId = searchInfo.value.unitId
            fjForms.value.buildingId = searchInfo.value.buildingId
            fjForms.value.floorId = searchInfo.value.floorId
            let res
            if (isRoomEdit.value) {
                res = await editRoom(fjForms.value)
            } else {
                res = await addRoom(fjForms.value)
            }
            if (res.code == 200) {
                ElMessage({
                    type: 'success',
                    message: isEdit.value ? '编辑成功' : '添加成功!'
                })
                getunitRoom()
            }
            dialog3.value = false
        }
    })
}
</script>

<style lang="scss" scoped>
.loudong-drawer {
    .bgl {
        background: #edf3fa;

        .active {
            color: #fff;
            background: #508ee5;
            padding: 10px;
            display: inline-block;
        }
    }

    .bgl-info {
        display: flex;
        margin: 14px 0;

        .item {
            display: flex;
            margin-right: 20px;
        }

        .label {}

        .value {
            color: #ffa200;
            margin-left: 10px;
        }
    }

    .floors {
        display: flex;
        background-color: #f2f2f2;

        .floor {
            padding: 10px 14px;
            cursor: pointer;
        }

        .active {
            background-color: #fff
        }
    }

    .section-title {
        font-weight: bold;
        font-size: 20px;
        line-height: 33px;
        padding: 8px 0 4px 14px;
        color: #4E7DFD;
        border-bottom: 1px solid #E7ECF1;
        position: relative;
        margin-bottom: 20px;
    }

    .section-title:before {
        content: '';
        position: absolute;
        top: 17px;
        left: 0;
        width: 6px;
        height: 14px;
        border-radius: 3px;
        background: #4E7DFD;
    }
}
</style>